/**
 * By Alpha
 * Author: alixez <alixe.z@foxmail.com>
 * Date: 2017/12/14
 */
import { jobService } from 'services';
import { config } from 'utils';
import { routerTool } from '../../utils';
import { message } from 'antd';

export default {
  namespace: 'organizationJob',

  state: {
    // 当前选择的部门
    firstLoaded: false,
    selectedJob: {},
    jobs: [],
    currentJob: {
      ID: "",
    },
    allUsers: [],
    selectedUsers: [],
    rightHasMore: true,
    leftHasMore: true,
  },

  reducers: {
    updateState (state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },

    addJob (state, { payload }) {
      const { job } = payload;
      state.jobs.push(job);

      return {
        ...state,
      };
    },

    doFirstLoad (state) {
      return {
        ...state,
        ...{
          firstLoaded: true,
        },
      };
    },

    changeCurrentJob (state, { payload: { job }}) {
      if ((state.currentJob || { ID: null }).ID !== job.ID) {
        return {
          ...state,
          ...{
            currentJob: job, 
          },
        };
      }
      return {
        ...state,
      };
    },
  },

  subscriptions: {
    setup ({ dispatch, history }) {
      return history.listen(location => {
        if (location.pathname === routerTool.getPathByName("OrganizationDepartment")) {
          dispatch({ type: 'watchCurrentJobUpdate' });
          dispatch({ type: 'loadJobs' })
            .then(() => {
              dispatch({ type: 'firstLoad' });
            })
            .then(() => {
              dispatch({
                type: 'loadAllUsers',
                payload: {
                  page: config.DefaultPager.page,
                  limit: config.DefaultPager.pageSize,
                },
              });
              dispatch({
                type: 'loadSelectedUsers',
                payload: {
                  page: config.DefaultPager.page,
                  limit: config.DefaultPager.pageSize,
                },
              });
            })
            .then(() => {
              dispatch({
                type: 'doFirstLoad',
              });
            });
        }
      });
    },
  },

  effects: {

    *firstLoad (_, { put, select }) {
      const { firstLoaded } = yield select(_ => _.organizationJob);
      // console.log(firstLoaded, '=== 首次加载状态');
      if (firstLoaded) {
        yield put({
          type: 'updateState',
          payload: {
            allUsers: [],
            selectedUsers: [],
          },
        });

        // const { allUsers } = yield select(_ => _.organizationJob);
        // console.log(allUsers, 'first allUsers');
      }

      // const { allUsers } = yield select(_ => _.organizationJob);
      // console.log(allUsers, 'first allUsers');
    },

    // 加载所有部门(当前社团)
    *loadJobs (_, { call, put }) {
      // 获取当前组织
      const { success, results } = yield call(jobService.getAllJobs);
      if (success) {
        const { Jobs } = results;
        
        // 更新职位列表
        yield put({
          type: 'updateState',
          payload: {
            jobs: Jobs,
            currentJob: Jobs[0],
          },
        });
      }
    },

    // 创建部门
    *createJob ({ payload }, { call, put, select }) {
      const { postData } = payload;

      // TODO create job
      const { success, results, message: msg } = yield call(jobService.createJob, postData);
      if (success) {
        const { Job } = results;
        yield put({
          type: 'addJob',
          payload: {
            job: Job,
          },
        });

        message.success('部门创建成功');
      } else {
        message.error(msg);
      }
    },

    // 加载所有用户
    *loadAllUsers ({ payload }, { call, put, select }) {
      // TODO load all can selected users
      const { isLoad, page, limit, reload } = payload;
      let { allUsers } = yield select(_ => _.organizationJob);
      // console.log(allUsers, 'second allUsers');
      if (reload) {
        allUsers = [];  
      }
      let params = {
        page: config.DefaultPager.page,
        limit: config.DefaultPager.pageSize,
      };

      if (isLoad) {
        params = { page, limit };
      }
      
      const { success, results } = yield call(jobService.allCanSelectedUsers, params);
      if (success) {
        const { List, PageSize, Total } = results;

        // 如果没有超页
        if (page <= Math.ceil(Total / PageSize) || Total === 0) {
          
          allUsers = allUsers.concat(List);
          yield put({
            type: 'updateState',
            payload: {
              allUsers,
            },
          });
        } else {
          yield put({
            type: 'updateState',
            payload: {
              rightHasMore: false,
            },
          });
        }
      }
    },

    // 加载被选择的用户（拥有该职位的用户）
    *loadSelectedUsers ({ payload }, { call, put, select }) {
      const { isLoad, page, limit, jobID, reload } = payload;
      // console.log(payload, 'HAHAHA');
      let { selectedUsers, currentJob } = yield select(_ => _.organizationJob);
      if (reload) {
        selectedUsers = [];
      }
      let params = {
        page: config.DefaultPager.page,
        limit: config.DefaultPager.pageSize,
      };

      if (isLoad) {
        params = { page, limit };
      }
      if (jobID) {
        params.jobID = jobID;
      } else {
        params.jobID = (currentJob || {}).ID;
      }
      
      // console.log(currentDept, 'dept ===');
      const { success, results } = yield call(jobService.getUsersWithJob, params);
      if (success) {
        const { List, PageSize, Total } = results;

        // 如果没有超页
        if (page <= Math.ceil(Total / PageSize) || Total === 0) {
          selectedUsers = selectedUsers.concat(List);
          
          yield put({
            type: 'updateState',
            payload: {
              selectedUsers,
            },
          });
        } else {
          yield put({
            type: 'updateState',
            payload: {
              leftHasMore: false,
            },
          });
        }
      }
    },

    // 将用户加到部门
    *addUserToJob ({ payload }, { call, put, select }) {
      const { users } = payload;
      
      const { currentJob, allUsers, selectedUsers } = yield select(_ => _.organizationJob);
  
      // console.log(users, '---- add ----');
      const { success } = yield call(jobService.addUsersToJob, {
        users,
        jobID: currentJob.ID,
      });
  
      if (success) {
        // 将操作的用户加入到被选择的列表
        const actionUsers = allUsers.filter(_ => users.includes(_.ID));
        yield put({
          type: 'updateState',
          payload: {
            selectedUsers: [
              ...selectedUsers,
              ...actionUsers,
            ],
          },
        });
        // 通知操作成功
        message.success('操作成功');
      } else {
        message.error('操作失败');
      }
    },
  
    // 将用户从部门移除
    *removeUserFromJob ({ payload }, { call, put, select }) {
      const { users } = payload;
      const { currentJob, selectedUsers, allUsers } = yield select(_ => _.organizationJob);
      // TODO 接口可能需要修改
      const { success } = yield call(jobService.removeUsersFromJob, {
        users,
        jobID: currentJob.ID,
      });
  
      if (success) {
        const changedSelectedUsers = selectedUsers.filter(_ => !users.includes(_.ID));
        // console.log(changedSelectedUsers, '被改变的用户');
        yield put({
          type: 'updateState',
          payload: {
            selectedUsers: changedSelectedUsers,
          },
        });
        yield put({
          type: 'loadAllUsers',
          payload: {
            reload: true,
            page: 1,
            limit: allUsers.length || config.DefaultPager.pageSize,
          },
        });
        message.success('操作成功');
      } else {
        message.error('操作失败');
      }
    },

    // 选中职位状态变更监听器
    watchCurrentJobUpdate: [function* ({ take, put }) {
      while (true) {
        const { payload: { job } } = yield take('changeCurrentJob');
        yield put({
          type: 'loadAllUsers',
          payload: {
            page: config.DefaultPager.page,
            limit: config.DefaultPager.pageSize,
            reload: true,
          },
        });
        yield put({
          type: 'loadSelectedUsers',
          payload: {
            jobID: job.ID,
            page: config.DefaultPager.page,
            limit: config.DefaultPager.pageSize,
            reload: true,
          },
        });
      }
    }, { type: 'watcher' }],
  },

};

